package eu.catlab.bbgs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class Util 
{
	public static String file_post_content (String url, String postdata)
	{
		String output = "";
		
		//System.out.println ("Fetching " + url);
		OutputStreamWriter wr = null;
		BufferedReader reader = null;
		
		try 
		{
			URL conurl = new URL(url);
			
			URLConnection conn = conurl.openConnection();
			
			conn.setDoOutput(true);
			
			if (postdata != null)
			{
				wr = new OutputStreamWriter(conn.getOutputStream());
				
				wr.write(postdata);
				wr.flush ();
			}
			
			reader = new BufferedReader (new InputStreamReader (conn.getInputStream()));

			String line = reader.readLine ();
		
			while (line != null)
			{
				output += "\n" + line;
				line = reader.readLine ();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			if(wr != null)
			{
				try {
					wr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(reader != null)
			{
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		
		output = output.substring(1);
		
		//System.out.println (output);
		
		return output;
	}
	
	private static String file_get_contents (String url)
	{
		return file_post_content (url, null);
	}
}
